package com.zlz.utils;

import com.zlz.entity.Goods;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:曾令忠
 * @Desc:
 * @Date 2020/8/9 0009 15:30
 */
public class HtmlParseUtil {

    public static void main(String[] args) throws Exception {
        for (Goods goods : parseJD("充气娃娃")) {
            System.out.println(goods);
        }
    }

    public static List<Goods> parseJD(String key) throws Exception {
        List<Goods> goodses = new ArrayList<>();

        String url = "https://search.jd.com/Search?keyword=" + key;
        //解析网页
        Document document = Jsoup.parse(new URL(url), 60000);
        Element element = document.getElementById("J_goodsList");
        Elements elements = element.getElementsByTag("li");
        for (Element el : elements) {
            String price = el.getElementsByClass("p-price").eq(0).text();
            if ("".equals(price)) {
                continue;
            }
            String title = el.getElementsByClass("p-name").eq(0).text();
            String img = el.getElementsByTag("img").eq(0).attr("src");
            Goods goods = new Goods(title, img, price);
            goods.setImg(img);
            goods.setPrice(price);
            goods.setTitle(title);
            goodses.add(goods);
        }
        return goodses;
    }
}
